package me.zxk.qwert_poetry.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import me.zxk.qwert_poetry.dao.User;
import me.zxk.qwert_poetry.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Optional;

@Component
public class JwtUtil {
    private static final int EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000; // 7 天
    private static final SecretKey secret = Keys.hmacShaKeyFor(System.getenv("JWT_SECRET").getBytes());

    /**
     * 生成 JWT Token 字符串
     * @param u 用户对象
     * @return JWT Token 字符串
     */
    public static String getJwtToken(User u) {
        return Jwts.builder()
                .subject(u.getId().toString())
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(secret)
                .compact();
    }

    public static Integer parseJwtToken(String token) {
        if (StringUtil.isNullOrEmpty(token)) {
            return null;
        }
        try {
            var claims = Jwts.parser().verifyWith(secret).build().parseSignedClaims(token);
            Date expiration = claims.getPayload().getExpiration();
            if (expiration.before(new Date()))
                return null;
            int id = Integer.parseInt(claims.getPayload().getSubject());
            return id;
        }
        catch (ApiException e) {
            return null;
        }
    }

}
